<template>
  <a-select
    :placeholder="$t('all.autotext1079')"
    :showArrow="false"
    mode="multiple"
    @change="change"
    :maxTagCount="1"
    v-model="value"
  >
    <a-select-option v-for="item in options" :key="item.value" :value="item.value">
      <a-tooltip :title="item.label">
        {{ item.label }}
      </a-tooltip>
    </a-select-option>
  </a-select>
</template>

<script>

function isArrayEqual (arr1, arr2) {
  const a1 = arr1.map((i) => i)
  let a2 = arr2.map((i) => i)
  let tempArr = []
  if (a1.length !== a2.length) {
    return false
  } else {
    for (let i = 0; i < a1.length; i++) {
      if (a2.indexOf(a1[i]) !== -1) {
        a2.splice(a2.indexOf(a1[i]), 1)
        tempArr.push(a1[i])
      } else {
        tempArr = []
        break
      }
    }
    return tempArr.length === arr2.length
  }
}
export default {
  props: {
    options: {
      type: Array,
      default: () => []
    }
  },
  data: function () {
    return {
      value: []
    }
  },
  watch: {
    options: {
      handler: function (val, oldVal) {
        const newOptions = val.map(i => i.value)
        const oldOPtions = oldVal.map(i => i.value)
        if (!isArrayEqual(newOptions, oldOPtions)) {
          this.initValue()
        }
      },
      deep: true
    }
  },
  mounted () {
    this.initValue()
  },
  methods: {
    initValue () {
      // if (!this.options.length) return
      const target = this.options.find(item => item.bindForPI)
      if (target) {
        this.value = [target.userId]
      } else {
        if (this.options.length === 1) {
          this.value = [this.options[0].userId]
        } else {
          this.value = []
        }
      }
      this.$emit('change', this.value)
    },
    change (value) {
      this.value = value
      this.$emit('change', this.value)
    }
  }
}
</script>

<style></style>
